<template>
  <div id="contactId" ref="contactRef">
    <div class="title">
      <span class="line"></span>
      <span>{{$t('wechat.mailList')}}({{  total==0?0:total}})</span>
          <el-button style="float:right;margin-left:10px;margin-right:10px;margin-top:6px;color:#fff;" type="text" @click="openPrintModel"><i class="el-icon-printer"></i> {{$t('wechat.dayinSms')}}</el-button>
    </div>
    <div class="inputBox" style="">
            <!-- <a-range-picker v-decorator="['range-picker', rangeConfig]" /> -->
            <a-input-search :placeholder="$t('wechat.phoneSearch')" v-model="searchWord" style="width: 100%;margin-bottom:10px;float:right;width: 99%;" @search="onSearchFirst" />
        </div>
    <div  class="contactBox" ref="list"  >

      <div class="item" style="" v-for="(item,index) in contantList" :key="index">
        <img
          height="60px"
          width="60px"
          src="../../../../assets/images/baseInfo/contact.png"
          alt=""
        />
        <div class="contactInfo">
          <div style="font-weight: bold" v-if="item.recovery !== 1">{{item.name}}</div>
          <div v-if="item.phone && item.recovery !== 1" :title="item.phone" >{{item.phone}}</div>

          <div style="font-weight: bold;color:red;" v-if="item.recovery == 1">{{item.name}}<span style="color:red;" v-if="item.recovery == 1">(已删除)</span></div>
          <div v-if="item.phone && item.recovery == 1" style="color:red;" :title="item.phone" >{{item.phone}}</div>
          
          <div v-if="item.other">{{item.other}}</div>
          <div>
        <div class="badgeBox" v-if="item.cntRemark>0">{{$t('wechat.remarked')}}</div>
          <el-button type="text" v-else @click="markOrder(item.phone,item.other,item.id,item.name)" size="mini" style="margin-right:20px;" icon="el-icon-edit">{{$t('wechat.biaoji')}}</el-button>
        </div>
        <el-button v-if="printShow" style="position: absolute;top: 15px;right: 50px;" @click="addPrint(item,$event)" type="text">添加</el-button>
        </div>  
        <!-- <div class="callDate">2022-02-15 10:25</div> -->
        <!-- <div class="stausType">
          <img
            height="40px"
            width="40px"
            src="../../../../assets/images/baseInfo/phone.png"
            alt=""
          />
        </div> -->
      </div>
      <div class="loadingBox" v-if="showLoading" style="color:#2196f3"><i :class="loadClass" style="color:#2196f3"></i> {{ loadingText }}</div>
      <a-affix :offset-bottom="50">
        <el-button type="primary" style="" @click="printJson" v-if="printShow">{{$t('wechat.startDaYin')}}</el-button>
        <el-button style="" @click="closePrintFunction" v-if="printShow">{{$t('wechat.close')}}</el-button>
       </a-affix>
      </div>
    <!-- 分页 -->
        <!-- <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="offset"
            :page-sizes="[20, 30, 40, 50]"
            :page-size="limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div> -->

    <a-modal width="300px" v-model="showRemark" :getContainer="getRefsAff"
      :maskClosable="false" title="提示"  @ok="handleOk">
      <p>{{$t('wechat.biaojibeizhu')}}</p>
      <p><el-input type="textarea" v-model="remark"></el-input></p>
    </a-modal>
    <!--打印窗口 -->
    <a-modal width="300px" v-model="showPrint" :getContainer="getRefsAff"
      :maskClosable="false" :title="$t('wechat.dayinyeshu')" @ok="printOk">
      <el-radio-group v-model="formResource">
          <el-radio :label="$t('wechat.linkuser')" style="margin-bottom:10px;font-size:18px;"></el-radio>
          <el-radio :label="$t('wechat.selfUser')" style="margin-bottom:10px;font-size:18px;"></el-radio>
          <el-radio :label="$t('wechat.jietu')" style="margin-bottom:10px;font-size:18px;"></el-radio>
        </el-radio-group>
    </a-modal>
  </div>
</template>

<script>
import print from 'print-js'
import html2canvas from "html2canvas"
import { parseTime } from "@/utils/index"
import { getContantApi,searchWord } from "@/api/baseInfo/base_api";
import { sendMarkOrderApi } from '@/api/markApi/index'
import { throttle } from 'lodash';

import ScreenShort from "js-web-screen-shot";
export default {
  name: "contact2",
  props: ["sendData"],
  data(){
      return{
      printShow:false,
      printArray:[],
      formResource:'打印所有联系人',
      scrollTop:0,
      itemData:'',
      loadClass:'el-icon-loading',
      loadingText:'正在加载. . .',
      showLoading:false,
      showPrint:false,
      pageIndexValue:'',
      dynamicTags:[],
      offset: 1,
      limit: 1000,
      total: 0,
      contantList:[],
      searchWord:'',
      showRemark:false,
      remark:'',
      id:'',
      phoneNumber:'',
      contactUsername:''
      }
  },
    watch: {
    "$store.state.account.contact2": function () {
      this.scrollTop = 0;
    if(this.sendData.list_offset){
      this.offset=1;
      this.limit=this.sendData.list_limit;
      this.searchWord = this.sendData.app_name;
    }else{
      this.offset=1;
    }
    this.contantList = [];
    this.onSearch();
    },
  },
  created(){
    this.scrollTop = 0
    if(this.sendData.list_offset){
      this.offset=1;
      this.limit=this.sendData.list_limit;
      this.searchWord = this.sendData.app_name;
    }else{
      this.offset=1;
    }
    this.contantList = [];
    this.onSearch();
  },
  methods:{
    addPrint(item,event){
      if(event.srcElement.innerHTML == '添加'){
        event.srcElement.innerHTML = '√已添加';
        event.srcElement.style.color = 'red';
        event.srcElement.style.fontWeight = '1000';
        this.printArray.push(item);
      }else{
        event.srcElement.innerHTML = '添加';
        event.srcElement.style.color = '#409EFF';
        event.srcElement.style.fontWeight = '500';
        const index = this.printArray.indexOf(item);
        if (index !== -1) {
          this.printArray.splice(index, 1);
        }
      }
    },
    closePrintFunction(){
      this.storeArray = [];
      this.printShow = false;
    },
    handleScroll(){
      // 获取列表元素
      const list = this.$refs.list;
      // 判断滚动到底部
      if (list.scrollTop + list.clientHeight+10+10 >= list.scrollHeight) {
        this.showLoading=true;
         
        if(this.contantList.length<this.total){
          this.loadClass = 'el-icon-loading';
          this.loadingText = '正在加载. . .';
          this.offset++;
          // 加载更多数据
          let that = this;
          // setTimeout(()=>{
            that.onSearch();
          // },1000)
        }else{
          this.loadClass = 'el-icon-success';
          this.loadingText = '到底了，没有更多了！';
        }
      }
    },
    addPageNumber(){
      if(this.pageIndexValue == '')return;
      if(this.dynamicTags.indexOf(this.pageIndexValue)==-1){
        this.dynamicTags.unshift(this.pageIndexValue);
        this.pageIndexValue = '';
      }else{
        this.$message({
            message: '第' + this.pageIndexValue + '页码已存在打印队列中！！',
            type: 'warning'
          });
        this.pageIndexValue = '';
      }
    },
    closeTags(tag){
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },
    openPrintModel(){
      // this.dynamicTags = [];
      this.showPrint = true;
    },
    printOk(){
      this.showPrint = false;
      switch (this.formResource) {
        case '打印所有联系人':
        this.printJson();
          break;
          
        case '手动添加联系人打印':
          this.scrollTop = this.$refs.list.scrollTop;
          this.printArray = [];
          this.printShow = true;
          // this.contantList = this.contantList.sort((a, b) => parseInt(b.msgtime) - parseInt(a.msgtime));
          break;
          
          case '对当前可视区域联系人截图':
            this.jietuFucntion()
            break;
      
        default:
          break;
      }
      
    },
    jietuFucntion(){
      
      
      // 获取当前页面的缩放比例
      const currentScale = window.devicePixelRatio;
      new ScreenShort({
        enableWebRtc: true, // 是否启用webrtc，值为false则使用html2canvas来截图
        loadCrossImg: true, // 跨域
        level: 999999999999999, // 层级
        // dpi: currentScale, // 设置 DPI
        // clickCutFullScreen:false,
        // wrcWindowMode:true
        
      });
      return
      const scrollContainer = this.$refs.list;


            this.$refs.list.style.letterSpacing = '3px';

            html2canvas(scrollContainer, {
              ignoreElements: (element) => {
                // console.log(element.id)
                // 返回 true 表示忽略该元素，这里我们忽略所有图片元素
                return element.tagName === 'IMG'  || element.tagName === "svg" || element.tagName === "img" || (element.tagName == 'SPAN' && element.id == 'chatId')
                || element.tagName === "HEADER"  || element.tagName === "div" || element.tagName === "I" 
                || element.tagName === "path" || element.tagName === "defs" || element.tagName === "symbol" || element.tagName === "NOSCRIPT" || element.tagName === "STYLE";
              },
              allowTaint: true,
              useCORS: true
            },).then((canvas) => {
              // 处理截图结果
              const imageData = canvas.toDataURL('image/png');
              console.log(imageData)
              // 创建一个下载链接
              const link = document.createElement('a');
              link.href = imageData;
              link.download = '123.png';

              // 触发点击事件以下载
              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link);
              this.$refs.list.style.letterSpacing = '0px';

            });
    },
    async printJson() {
      let oldContant = this.contantList;
      if(this.formResource == '手动添加联系人打印'){
        this.contantList = this.printArray;
      }
      //通过getdata调用后台接口获取数据封装到res
      const res = await this.getPrintJsonStr();
      let that = this;
      setTimeout(()=>{
        let data = that.contantList
        let focuser = setInterval(() => window.dispatchEvent(new Event('focus')), 500);
      
      printJS({
        printable: data,
        maxWidth:800,
        properties: [
          {
            field: 'id',
            displayName: '序号',
            columnSize: '10%'
          },
          {
            field: 'name',
            displayName: '联系人姓名',
            columnSize: '20%'
          },
          {
            field: 'phone',
            displayName: '手机号',
          },
          {
            field: 'other',
            displayName: '其他',
          },
          
        ],
        type: 'json',
        header: '通讯录',
        documentTitle:'-',
        headerStyle:'font-size:18px;',
        // 样式设置
        gridStyle: 'border: 1px solid #000;text-algin:center;tr{width:200px;}',
        gridHeaderStyle: 'color:#000;  border: 1px solid #000;',
        onPrintDialogClose: () => {
          clearInterval(focuser);
          console.log(111)
          that.contantList = oldContant;
          that.printShow = false;
          that.$nextTick(() => {
            that.$refs.list.scrollTop=that.scrollTop;
              })
        }
      })
      },1000)
    },    
    getPrintJsonStr(){
      // this.dynamicTags = []
      let list = []

      for (let index = 0; index < this.dynamicTags.length; index++) {
        const element = this.dynamicTags[index];

        let data={
            proof_num: this.sendData.proof_num,
            searchkey:this.searchWord,
            model:this.sendData.model,
            offset: Number(element),
            limit: 20,
        }
        searchWord(data,'/search/contact').then(res=>{
              let item = {
                pageIndex:element,
                list:res.data
              }
              list.push(item);
        })
        
      }
      return list;

    },
    getRefsAff(){
      return  this.$refs.contactRef;
    },
    handleOk(){
        this.scrollTop = this.$refs.list.scrollTop;
        let data={
          navigation_list:sessionStorage.getItem('arr').split(','),
          model:this.sendData.model,
          isChat:0,
          app_name:this.phoneNumber!==''?this.phoneNumber:this.contactUsername,
          account_id:'',
          proof_num:this.sendData.proof_num,
          list_offset:this.offset,
          list_limit:this.limit,
          remark:this.remark,
          class:this.sendData.class,
          label:this.sendData.label,
          id:Number(this.id)
      }
      // return
      sendMarkOrderApi(data).then(res=>{
        this.showRemark=false;
        this.$message({
          message: '标记数据成功！',
          type: 'success'
        });
        this.contantList = [];
        this.onSearch()
        
      })
    },
    // 添加标记点
    markOrder(phone,other,id,name){
      this.id=id;

      this.contactUsername = name;
      this.phoneNumber = phone==''?other:phone;
      this.showRemark=true;
    },
    onSearchFirst:throttle(function(){
      this.contantList = []
      this.offset=1
      this.onSearch()
    },2000),
  
    onSearch(){
      if(sessionStorage.getItem('searchAll')!==null){
        this.searchWord = sessionStorage.getItem('searchAll');
        this.contantList = [];
      }
      let data={
          proof_num: this.sendData.proof_num,
          searchkey:this.searchWord,
          model:this.sendData.model,
          offset: this.offset,
          limit: this.limit,
      }
      searchWord(data,'/search/contact').then(res=>{
        let that = this
              this.$nextTick(() => {
                this.$refs.list.scrollTop=that.scrollTop;
              })

        if(res.data.length == 0){
          this.loadClass = 'el-icon-success';
          this.loadingText = '到底了，没有更多了！';
          return
        }else if(res.data.length == 1){
             this.loadClass = 'el-icon-success';
            this.loadingText = '到底了，没有更多了！';
        }
        for (let index = 0; index < res.data.length; index++) {
          const element = res.data[index];
          this.contantList.push(element);
        }
        

        if(this.sendData.app_name){
          for (let index = 0; index < this.contantList.length; index++) {
            const element = this.contantList[index];
            if(element.phone == this.sendData.app_name){
            }
          }
        }
        try {
        this.total=res.data[0].cnt
        } catch (error) {
        }
      })
    },
    // 格式化时间
    formateTime(date){
     return parseTime(date)
    },
    handleSizeChange(val) {
      this.limit=val
      this.onSearch()
    },
    handleCurrentChange(val) {
      this.offset=val
      this.onSearch()
    }
  }
};
</script>

<style scoped>
#contactId {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  flex: 1 1 auto;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
  min-height: 0;
}

.inputBox {
flex: 0 0 auto;
}

.loadingBox {
  text-align: center;
}

.badgeBox {
  width: 50px;
  height: 23px;
  border-radius: 10px;
  color: #fff;
  background: #f56c6c;
  text-align: center;
  line-height: 23px;
  position: absolute;
  font-size: 12px;
  top: -10px;
  right: -10px;
}

.block {
  text-align: center;
}

.fenPages {
  text-align: center;
}

.contactBox {
  padding: 10px 1%; 
  width: 100%;
  min-width: 300px;
  padding-bottom: 20px;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  scrollbar-gutter: stable;
  scrollbar-width: thin;
  scrollbar-color: #c0c0c0 rgb(252, 252, 252);
  flex: 1;
  min-height: 0;
  height: 100%;
  overscroll-behavior: contain; /* 阻止滚动链到整页 */
  display: flex;
  flex-direction: column;
}

.contactBox::-webkit-scrollbar {
  width: 8px;
}

.contactBox::-webkit-scrollbar-track {
  background-color: rgb(252, 252, 252);
  border-radius: 2em;
}

.contactBox::-webkit-scrollbar-thumb {
  background-color: #c0c0c0;
  border-radius: 2em;
}

.title {
  width: 100%;
  height: 50px;
  background: #2b2f3a;
  font-size: clamp(14px, 1.5vw, 18px);
  line-height: 50px;
  padding-left: 20px;
  color: #fff;
  flex-shrink: 0;
}

.line {
  width: 8px;
  height: 100%;
}

.item {
  width: 98%;
  margin: 0 auto;
  min-height: 80px;
  border: 1px solid rgb(235, 235, 235);
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
  border-radius: 5px;
  background: rgb(253, 253, 253);
  cursor: pointer;
  position: relative;
  transition: transform 0.2s ease;
}

.item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.contactInfo {
  padding: 0 20px;
  flex: 1;
  min-width: 0;
  overflow: hidden;
}

.contactInfo div {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

img {
  width: 60px;
  height: 60px;
  object-fit: contain;
  flex-shrink: 0;
}
</style>
